package com.ashion.findfuny;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.ProgressBar;

public class MainActivity extends Activity {

	private static final String TAG = MainActivity.class.getSimpleName();
	private Context mContext;
	private ListView listView;
	private MainListAdapter listAdapter;
	//private MainListScrollListener listScrollListener;
	private List<Map<String, Object>> listData;
	private boolean needRefresh;
	private boolean isUpdating = false;
	public int screenHeight;
	
	private static final int SCALL_UPDATE_START = 1;
	private static final int SCALL_UPDATE_FINISH = 2;
	
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			switch(msg.what){
			case SCALL_UPDATE_START:
				isUpdating = true;
				listAdapter.setProgressVisiable(true);
				doListViewRefresh();
				break;
			case SCALL_UPDATE_FINISH:
				isUpdating = false;
				if(needRefresh){
					listAdapter.notifyDataSetChanged();
				}
				listAdapter.setProgressVisiable(false);
				break;
			default:
				break;
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		
		DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
		screenHeight = metric.heightPixels;
		
		listView = (ListView)findViewById(R.id.list_view);
		listData = initListData(listData);
		
		Log.v(TAG, "ashion log----->data count="+listData.size());
		listAdapter = new MainListAdapter(mContext, listView, listData);
		listView.setAdapter(listAdapter);
		listView.setOnScrollListener(new MainListScrollListener(callBack));
		
	}

	
	ReFreshCallBack callBack = new ReFreshCallBack(){    
        public void execute() {    
        	if(!isUpdating){
                mHandler.sendEmptyMessage(SCALL_UPDATE_START);
                Log.v(TAG, "ashion log------------list end");
        	}
        }
	};
    
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	
	private List<Map<String, Object>> initListData(List<Map<String, Object>> listData){
		if(listData == null)
			listData = new ArrayList<Map<String, Object>>();
		for(int i=0;i<5;i++){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put(CommonUtil.IMAGE, "http://www.baidu.com/img/baidu_sylogo1.gif");
			map.put(CommonUtil.TITLE, "Hello world");
			map.put(CommonUtil.USER, "Ashion");
			map.put(CommonUtil.COUNT, "122");
			listData.add(map);
		}
		return listData;
	}
	
	private void doListViewRefresh(){
		new Thread(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(3000l);
					Random random = new Random();
					int flg = random.nextInt(2);
					Log.v(TAG, "randowm==flg=="+flg);
					if(flg == 0){
						needRefresh = true;
						listData = initListData(listData);
					}else{
						needRefresh = false;
					}
					mHandler.sendEmptyMessage(SCALL_UPDATE_FINISH);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
	}
	
	public interface ReFreshCallBack {
		void execute();
	}
	
	public class MainListScrollListener implements OnScrollListener{

		private ReFreshCallBack mCallback;

		public MainListScrollListener(ReFreshCallBack callback) {
		    this.mCallback = callback;
		}
		
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub
			if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
	            if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
		           	 //int[] location = new int[2];
		           	 //View v = (View) view.getChildAt(view.getChildCount() - 1);
		             //v.getLocationOnScreen(location);
		             //int y = location[1];
		             //Log.v("screenHeight height", ""+screenHeight+" ----v height="+v.getHeight());
		             //Log.d("x" + location[0], "y" + location[1]+"----view.getLastVisiblePosition()="+view.getLastVisiblePosition());
		             //if ((y + v.getHeight()) == screenHeight){
		            	 mCallback.execute();
		             //}
	            }
			}
		}

	}
}
